import anime from 'animejs'
import { edgeConfig } from '../config/edgeConfig'
import { sizeConfig } from '../config/sizeConfig'
import { BoolType, IDataValue, IModuleWithState } from '../types'
import {
    createDataValue,
    getCenterPoint,
    setDomBoolVal,
    toBinaryStr,
} from '../utils'
import { bus1 } from './bus'
import { conSignal } from './conSignal'
import { decoder } from './decoder'

interface IIrState {
    ld_ir: BoolType
    value: number
}

interface IIr extends IModuleWithState<IIrState> {
    dataItem: IDataValue<number> | null
}

/**
 * ir模块
 */
export const ir: IIr = {
    name: 'ir',
    dataItem: null,
    state: {
        ld_ir: 1,
        value: 0,
    },
    async setState(prop, value) {
        this.state[prop] = value
        setDomBoolVal(prop, this.state[prop] as BoolType)
        return
    },
    async neg() {
        // 在时钟下降沿触发时
        if (this.state.ld_ir === 1) {
            // 在时钟的下降沿，从bus1中拿数据送到decoder
            // bus1中的数据
            const val = bus1.getData()
            this.state.value = val
            // ir的底部中心点
            const irBottomCenterPoint = getCenterPoint(sizeConfig.ir, 'bottom')
            this.dataItem?.setPosition(irBottomCenterPoint)
            this.dataItem?.setText(toBinaryStr(val))
            // decoder的底部中心点
            const decoderBottomCenterPoint = getCenterPoint(
                sizeConfig.decoder,
                'bottom'
            )
            // 动画
            return anime({
                targets: this.dataItem?.dom,
                x: decoderBottomCenterPoint.x,
                y: decoderBottomCenterPoint.y,
                duration: (edgeConfig.time.neg + edgeConfig.time.low) * 0.1,
                easing: 'linear',
                complete: () => {
                    // 通知decoder模块，ir的值发生了变化
                    decoder.change!()
                    conSignal.change()
                },
            }).finished
        }
    },
    init() {
        // 设置ld_ir的初始值
        // setDomBoolVal('ld_ir', this.state.ld_ir)
        // this.state.value = bus1.getData()
        // decoder的底部中心点
        const decoderBottomCenterPoint = getCenterPoint(
            sizeConfig.decoder,
            'bottom'
        )
        // 要做动画的数据
        this.dataItem = createDataValue(
            this.state.value,
            toBinaryStr(this.state.value),
            decoderBottomCenterPoint
        )
    },
}
